import Joi from "joi";

import {responseJson} from "~/server/utils/helper";
// @ts-ignore
import jwt from 'jsonwebtoken'
import {Md5} from 'ts-md5'
import { PrismaClient } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';
const prisma = new PrismaClient();

export const secret='shhhhh'
export default defineEventHandler(async (event) => { 

    const body = await readBody(event)
    // 参数校验
    const schema =Joi.object( {
        username: Joi.string().required(),//.pattern(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/)
        password: Joi.any().required()
    }).with('phone','password')
    try {
        // 验证
        const test = await schema.validateAsync(body)
    } catch (e) {
        return responseJson(1,'参数错误',{});
    }
    
    try {
        // 查询账号密码
        const rows=await prisma.user.findFirst({ where: { username: body.username} });
        if (!rows) {
            return responseJson(1,'账号不存在或密码错误~',{})
        }
        let md5: any = new Md5()
        // 密码加密
        let newPassword = md5.appendStr(body.password + rows.salt).end().toString()
        if(rows.password!== newPassword){
            return responseJson(1,'账号不存在或密码错误~',{})
        }
        
        let token = jwt.sign({data: {uid:rows.id} ,exp: Math.floor(Date.now() / 1000) + (60*60),}, secret);
        let refreshToken = jwt.sign({data: {uid:rows.id} ,exp: Math.floor(Date.now() / 1000) + (60  *60* 24 * 7),}, secret);
        const uuid=uuidv4()
        await useStorage('redis').setItem(uuid, token,{ ttl: Math.floor(Date.now() / 1000) + (60)})
        await useStorage('redis').setItem(refreshToken, token,{ ttl: Math.floor(Date.now() / 1000) + (60 * 60*24*7)})
        return responseJson(0,'ok',{accessToken:uuid,refreshToken:refreshToken})
    }catch (e) {
        return responseJson(1,'服务器错误~',{})
    }

})